    package ch.bfh.swos.learnaid.service.impl;

import java.lang.reflect.Type;
import java.util.Collection;

import javax.inject.Inject;
import javax.inject.Named;

import org.modelmapper.ModelMapper;
import org.modelmapper.TypeToken;

import ch.bfh.swos.learnaid.model.Question;
import ch.bfh.swos.learnaid.repository.QuestionRepository;
import ch.bfh.swos.learnaid.service.QuestionService;
import ch.bfh.swos.learnaid.service.dto.QuestionDTO;

@Named
public class DefaultQuestionService implements QuestionService{

    @Inject
    private QuestionRepository questionRepository;

    private final ModelMapper mapper = new ModelMapper();
    
    @Override
    public QuestionDTO create(QuestionDTO questionDto) {
        Question question = mapper.map(questionDto, Question.class);
        Question persistedQuestion = questionRepository.save(question);
        return mapper.map(persistedQuestion, QuestionDTO.class);
    }

    @Override
    public QuestionDTO read(long id) {
        Question author = questionRepository.findOne(id);
        if (author == null) return null;
        return mapper.map(author, QuestionDTO.class);
    }

    @Override
    public Collection<QuestionDTO> list() {
        Iterable<Question> questions = questionRepository.findAll();
        Type listType = new TypeToken<Collection<QuestionDTO>>() {
        }.getType();
        return mapper.map(questions, listType);
    }

    @Override
    public QuestionDTO update(QuestionDTO questionDTO) {
        Question question = mapper.map(questionDTO, Question.class);
        Question updatedQuestion = questionRepository.save(question);
        return mapper.map(updatedQuestion, QuestionDTO.class);
    }

    @Override
    public void delete(QuestionDTO questionDTO) {
            Question question= questionRepository.findOne(questionDTO.getId());
            questionRepository.delete(question);
        
    }

}
